package demo.controller;

import demo.dao.UserMapper;
import demo.dao.UserMapper1;
import jdbc.InputUtil;
import jdbc.UserInfo;
import java.util.Scanner;

public class UserController {
    private final UserMapper userMapper = new UserMapper();
    private final UserMapper1 userMapper1 = new UserMapper1();
    public void start() {
        System.out.println("欢迎使用用户管理系统");
        System.out.println("请输入要进行操作的编号:");
        System.out.println("[1]:用户注册");
        System.out.println("[2]:用户登录");
        System.out.println("[3]:修改密码");
        Scanner scanner = new Scanner(System.in);
        String num = scanner.nextLine();
        switch (num){
            case "1":
                regUser();
                break;
            case "2":
                loginUser();
                break;
            case "3":
                changePWD();
                break;
            default:
                System.out.println("编号输入有误");
        }
    }
    public void regUser(){
            UserInfo userInfo = InputUtil.getInputObject(new UserInfo(),"注册用户", "注册");
            if(userMapper.findByUsername(userInfo.getUsername()) != null){
                System.out.println("用户名已存在，请重新输入");
                regUser();
            }
        System.out.println(userMapper.insert(userInfo) > 0 ? "注册成功" : "注册失败");
    }
    public void loginUser(){
            UserInfo userInfo = InputUtil.getInputObject(new UserInfo(),"用户登录", "登录");
            System.out.println(userMapper.verify(userInfo) != null ? "登录成功" : "用户名或密码错误");
    }
    public void changePWD(){
//           UserInfo userInfo = InputUtil.getInputObject(new UserInfo(),"修改密码", "修改密码");
//           if(userMapper.verify(userInfo) == null){
//               System.out.println("用户名或密码错误");
//           }else{
//               System.out.println(userMapper.updatePassword(userInfo) > 0 ? "修改成功" : "修改失败");
//           }
        Scanner scanner = new Scanner(System.in);
        System.out.println("修改密码");
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();
        System.out.println("请输入旧密码:");
        String oldPassword = scanner.nextLine();
        System.out.println("请输入新密码:");
        String newPassword = scanner.nextLine();
        UserInfo userInfo = userMapper1.findByUsername(username);
        if(userInfo == null){
            System.out.println("用户名不存在");
        }else if(!userInfo.getPassword().equals(oldPassword)){
            System.out.println("密码错误");
        }else{
            userInfo.setNewPassword(newPassword);
            System.out.println(userMapper1.update(userInfo) > 0 ? "修改成功" : "修改失败");
        }
    }
    public static void main(String[] args) {
        UserController userController = new UserController();
        userController.start();
    }
}
